<template>
	<view class="order order-index">
		<view class="title">
			收货地址
		</view>
		<!-- 地址 -->
		<view class="address-body flex-row-around" @click="choseAddress">
			<view class="address-info flex-column-around">
				<view class="address" style="font-size: 14px;color: #666;">
					{{address.recvAddr}}
				</view>
				<view class="details-address" style="font-weight: bold;">
					{{address.recvAddr}}
				</view>
				<view class="propleandphone" style="font-size: 14px;color: #666;">
					{{address.recvPerson}} {{address.recvTel}}
				</view>
			</view>
			<view class="icon flex-column-center" @click="choseAddress">
				<uni-icons 
					type="right"
					size="20">
				</uni-icons>
			</view>
		</view>
		<view class="title">
			订单信息
		</view>
		<view class="order-info" style="width: 700rpx;margin: 0 auto;">
			<view class="orderno" style="width: 700rpx;height: 40px;
										 border-radius: 10px;background-color: white;
										 line-height: 40px;padding: 0 10px;box-sizing: border-box;">
				订单编号: {{orderInfo.ordersno}}
			</view>
		</view>
		<view class="title">
			订单所含产品
		</view>
		<!-- 商品 -->
		<view class="product-body" v-for="item in productList" :key="item">
			<view class="delete" @click="removeProduct(item)">
				<uni-icons type="trash-filled" size="25" color="red"></uni-icons>
			</view>
			<view class="product flex-row-around">
				<view class="product-image">
					<view class="image">
						<image :src="baseUrl+item.productImage"></image>
					</view>
				</view>
				<view class="product-info">
					<view class="product-name">
						{{item.productName}}
					</view>
					<view class="product-price flex-row">
						<view class="price">
							<text>￥</text>
							<text style="font-size: 20px;">{{item.productPrice}}</text>
						</view>
						<view class="control-num" v-if="item.productType==1">
							<uni-number-box 
								v-model="item.ordersNum" 
								@change="changeValue"
								:min="1"/>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="get-free" v-if="productType==1"
			  style="width: 700rpx;height: 40px;
					 margin: 0 auto;text-align: center;line-height: 40px;
					 font-weight: bold;box-sizing: border-box;">
			<text @click="choseGive">选择赠送内容</text>
		</view>
		<view class="nothing"></view>
		<!-- 底部 -->
		<view class="bottom-my flex-row">
			<view class="all-price">
				<text>￥</text> 
				<text style="font-size: 20px;font-weight: bold;">{{allPrice}}</text>
			</view>
			<view class="button continue" @click="coutinue">
				<text>继续逛逛</text>
			</view>
			<view class="button submit" @click="toggle('bottom')">
				<text>提交订单</text>
			</view>
		</view>
	</view>
	<!-- 弹窗 -->
	<view class="dia">
		<uni-popup border-radius="20px 20px 0 0" ref="popup" :type="type" v-show="true" backgroundColor="#eee" style="overflow: auto;">
			<view class="top">
				<view class="price">
					<text>￥</text>
					<text style="font-size: 20px;font-weight: bold;">{{allPrice}}</text>
				</view>
			</view>
			<view class="pay-type flex-row">
				<view class="left flex-row">
					<view class="pay-icon">
						<image src="https://img1.baidu.com/it/u=1471529724,2678837426&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1717174800&t=62f0fd5c2a8703e362c3ea58e3906439" alt="" />
					</view>
					<view class="pay-name">
						微信支付
					</view>
				</view>
				<view class="right">
					<label class="radio">
						<radio value="1" checked="true"/>
					</label>
				</view>
			</view>
			<view class="yes-button">
				<view class="btn-body" @click="topay()">
					确认付款
				</view>
			</view>
			<view class="yes-button" v-if="userInfo.paySpecmode == 1">
				<view class="btn-body" @click="simulation()">
					模拟支付
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import { BASE_IMAGE_URL, GET_USER_INFO } from '/utils/CommonValues.js';
	import request from '../../../utils/request.js'
	export default {
		data() {
			return {
				userInfo: '',
				orderInfo: '',
				baseUrl: '',
				address: {},
				type: 'bottom',
				msgType: 'success',
				messageText: '这是一条成功提示',
				value: '',
				productList: [],
				allPrice: 0,
				productType: 1
			}
		},
		onLoad(option) {
			this.productType = option.type;
			this.baseUrl = BASE_IMAGE_URL;
			GET_USER_INFO().then(response => {
				this.userInfo = response;
				this.getProductList();
				this.getDefaultAddress('1', '');
			})
		},
		onShow() {
			// this.getDefaultAddress('1', '');  
			uni.$on("update-address", (id) => {
				console.log("修改订单触发")
				this.getProductList();
				this.getDefaultAddress('', id);
			})
		},
		methods: {
			choseGive() {
				uni.navigateTo({
					url: '/pages/product/give/give'
				})
			},
			simulation(){
				request.PUT("/system/orders", {
				    advOrdersId: this.orderInfo.advOrdersId,
				    orderStatus: 2,
					advMembersId: this.userInfo.advMembersId
				}).then(response => {
				    uni.showToast({
				        title: '支付成功',
				        icon: 'success',
				        duration: 500,
				        complete: () => {
				            uni.redirectTo({
				                url: '/pages/my/orders/orders'
				            });
				        }
				    });
				})
			},
			//支付
			topay(){
				const orderInfo = this.orderInfo;
				request.POST("/system/wx-pay/jsapi",{
					advOrdersId: orderInfo.advOrdersId,
					weOpenid: orderInfo.weOpenid,
					productName: '产品',
					ordersamount: this.allPrice,
					productDesc: '产品描述',
					ordersno: orderInfo.orderno
				}).then(response =>{
					console.log("response--->",response);
					  wx.requestPayment({
						"timeStamp": response.data.timeStamp,
					    "nonceStr": response.data.nonce,
					    "package": "prepay_id="+response.data.prepay_id,
					    "signType": "RSA", 
					    "paySign": response.data.signature,
						success: function(res) {
							console.log("advOrdersId-->",orderInfo);
							request.POST("/system/wx-pay/payOver", {
							    advOrdersId: orderInfo.advOrdersId,
							    orderStatus: 2
							}).then(response => {
							    uni.showToast({
							        title: '支付成功',
							        icon: 'success',
							        duration: 500,
							        complete: () => {
							            uni.redirectTo({
							                url: '/pages/my/orders/orders'
							            });
							        }
							    });
							})
							console.log('支付成功：', res);
						},
						fail: function(res) {
						// 支付失败
							console.log('支付失败：', res);
							uni.showToast({
								title: '支付失败，请重试',
								icon: 'none',
								duration: 2000
							});
						// 在这里处理支付失败后的逻辑，例如提示用户重新支付等
						},
						complete: function(res){
							console.log('结束：', res);
						}
				  });
					
				}).catch(error => {
					uni.showToast({
						title: '未知错误',
						icon: 'none',
						duration: 2000
					});
				})
			},
			// 修改订单收货地址信息
			updateOrderAddress() {
				console.log(this.orderInfo, '订单信息')
				request.PUT('/system/orders', {
					advOrdersId: this.orderInfo.advOrdersId,
					advMembersaddrId: this.address.advMembersaddrId
				}).then(response => {
					console.log(response, '修改订单地址');
				}).catch(error => {
					console.log("未知错误");
				})
			},
			// 获取地址 参数一：是否为默认地址  参数二：地址的id
			getDefaultAddress(isDefault, advMembersaddrId) {
				request.GET('/system/membersaddr/list', {
					advMembersId: this.userInfo.advMembersId,
					recvDefault: isDefault,
					advMembersaddrId: advMembersaddrId
				}).then(response => {
					if(response.rows.length == 0) {
						uni.showModal({
							title: '没有默认地址,请先添加默认地址',
							complete(e) {
								console.log(e)
								if(e.cancel) {
									uni.navigateBack();
								} 
									
								if(e.confirm) {
									uni.navigateTo({
										url: '/pages/my/address/address'
									})
								}
							}
						})
					} else {
						this.address = response.rows[0];
						this.updateOrderAddress();
						console.log(response, `地址信息${advMembersaddrId}`);
					}
				})
			},
			// 获取到未付款订单的产品数据
			getProductList() {
				request.GET(`/system/orders/bymembersid/${this.userInfo.advMembersId}/${this.productType}`, null)
				.then(res => {
					this.orderInfo = res.data;
					console.log("获取到订单数据: ", this.orderInfo)
					if(this.orderInfo) {
						// 根据订单id获取到产品清单信息
						request.GET(`/system/ordersdetail/list/app/${this.orderInfo.advOrdersId}`, null).then(r => {
							this.productList = r.rows;
							// console.log(this.productList)
							this.changeValue();
						})
					} else {
						uni.showModal({
							title: '没有可结算订单',
							complete() {
								uni.navigateBack();
							}
						})
					}
				})
			},
			// 继续逛逛
			coutinue() {
				uni.switchTab({
					url: '/pages/product/product'
				})
			},
			// 选择地址
			choseAddress() {
				uni.navigateTo({
					url: '/pages/my/address/address?pageName=order'
				})
			},
			submit() {
				
			},
			//弹窗开启
            toggle(type) {
                this.type = type
                this.$refs.popup.open(type)
				console.log("我的productList()",this.productList);
				// 发送请求到后端更新订单明细中的数量
            let orderDetails = this.productList.map(item => ({
                advOrdersdetailId: item.advOrdersdetailId,
                ordersNum: item.ordersNum
            }));
            request.POST("/system/orders/updateByNum", orderDetails)
                .then(response => {

                })
			},
			// 数量改变 重新计算总价
			changeValue(){
				this.allPrice = 0;
				for(var i = 0; i < this.productList.length; i++) {
					this.allPrice += this.productList[i].productPrice 
									 * this.productList[i].ordersNum;
				}
				// 修改订单的金额
				request.PUT(`/system/orders`, {
					advOrdersId: this.orderInfo.advOrdersId,
					ordersamount: this.allPrice
				}).then(response => {
					console.log("修改金额完成")
				})
			},
			// 从订单列表移除产品
			removeProduct(product) {
				// 需要发送请求到后端删除对应产品的产品清单信息
				request.DELETE(`/system/ordersdetail/${product.advOrdersdetailId}`, null)
				.then(response => {
					this.getProductList();
				})
			}
 		}
	}
</script>

<style lang="less">
.title {
	box-sizing: border-box;
	width: 700rpx;
	height: 30px;
	line-height: 30px;
	margin: 10px auto;
	border-left: 5px solid orangered;
	padding-left: 10px;
	font-weight: bold;
}
.order{
	width: 750rpx;
	height: 100vh;
	overflow-y: auto;
	position: relative;
}
.address-body {
	width: 700rpx;
	height: 100px;
	background-color: white;
	border-radius: 10px;
	margin: 10px auto;
	.address-info {
		width: 80%;
		height: 100%;
		align-items: start;
		box-sizing: border-box;
		padding-left: 10px;
	}
	.icon {
		width: 15%;
		height: 100%;
	}
}
.product-body {
	width: 700rpx;
	height: 100px;
	background-color: white;
	border-radius: 10px;
	margin: 10px auto;
	position: relative;
	.delete {
		position: absolute;
		right: 0;
		top: 0;
		width: 30px;
		height: 30px;
	}
	.product-image {
		width: 28%;
		height: 100px;
		.image {
			width: 160rpx;
			height: 80%;
			margin: 10px;
			border-radius: 10px;
			image {
				border-radius: 10px;
			}
		}
	}
	.product-info {
		width: 70%;
		height: 100px;
		.product-name {
			width: 100%;
			height: 50px;
			line-height: 50px;
		}
		.product-price {
			width: 100%;
			height: 40px;
			align-items: flex-end;
			color: red;
			font-weight: bold;
		}
	}
}
@bottom-hight-my: 70px;
.nothing {
	height: @bottom-hight-my;
}
.bottom-my {
	width: 750rpx;
	height: @bottom-hight-my;
	position: fixed;
	left: 0;
	bottom: 0;
	background-color: white;
	box-sizing: border-box;
	padding: 0 20px;
	z-index: 99;
	.all-price {
		color: red;
		font-weight: bold;
		margin-bottom: 15px;
	}
	.button {
		width: 200rpx;
		height: 40px;
		border-radius: 20px;
		background-color: orangered;
		color: white;
		text-align: center;
		line-height: 40px;
		font-weight: bold;
		margin-bottom: 15px;
	}
	.continue {
		background-color: #eee;
		color: #666;
	}
	.submit {
		width: 300rpx;
		&:active {
			background-color: coral;
		}
	}
}
.dia {
	.top {
		width: 750rpx;
		text-align: center;
		height: 40px;
		line-height: 40px;
		margin-top: 10px;
	}
	.pay-type {
		width: 700rpx;
		height: 60px;
		background-color: #fff;
		margin: 0 auto;
		border-radius: 10px;
		box-sizing: border-box;
		.left {
			width: 300rpx;
			height: 100%;
			justify-content: flex-start;
			.pay-icon {
				width: 40px;
				height: 40px;
				margin: 10px;
			}
			.pay-name {
				font-weight: bold;
			}
		}
		.right {
			width: 40px;
			height: 40px;
			margin-top: 10px;
		}
	}
	.yes-button {
		width: 750rpx;
		height: 60px;
		.btn-body {
			width: 700rpx;
			height: 40px;
			margin: 20px auto 0;
			border-radius: 20px;
			background-color: orangered;
			text-align: center;
			font-weight: bold;
			color: #fff;
			line-height: 40px;
			&:active {
				background-color: coral;
			}
		}
	}
}

</style>
